package com.example.player.controller;

import com.example.player.entity.User;
import com.example.player.entity.dto.UserLoginDTO;
import com.example.player.entity.dto.UserRegDTO;
import com.example.player.service.IUserService;
import com.example.player.web.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author fendou2021
 * @create 2022-04-17 21:38
 */
@RestController
@RequestMapping(value = "/user",produces = "application/json")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/reg")
    public JsonResult<Void> reg(@RequestBody @Valid UserRegDTO userRegDTO){
        userService.reg(userRegDTO);
        //此处需要将JsonResult转换String类型再返回,否则会出现HTTP的406异常:Could not find acceptable representation
        //这样处理是不合适的 如果这样返回,判断用户名是否重复的逻辑就失效了
        //解决方案:在JsonResult中加上get/set方法,并在Controller类的RequestMapping上加上了produces = "application/json"属性
        // --- 2022.4.17
        return JsonResult.ok();
    }

    @PostMapping("/login")
    public JsonResult<Void> login(@RequestBody @Valid UserLoginDTO userLoginDTO, HttpSession session){
        //商城首页应该根据是否是登录状态来动态修改前端的超链接,如果已经是登录状态不应该再有Sign In和Join Free的超链接,
        //而应该显示Logout(退出登录)的超链接,可以在进入页面时获取session对象,来判断是否是登录状态,并且定义变量isLogin表示这个状态,
        //用Vue的V-if标签来判断显示哪些超链接
        userService.login(userLoginDTO,session);
        return JsonResult.ok();
    }

    @GetMapping("/getCurrentUser")
    public User getCurrentUser(HttpSession session){
        User user = userService.getCurrentUser(session);
        return user;
    }

    @GetMapping("/logout")
    public JsonResult<Void> logout(HttpSession session) {
        userService.logout(session);
        return JsonResult.ok();
    }
}
